<?php

namespace App\Http\Controllers;

use App\Events\WithdrawalEvent;
use App\Jobs\Queue;

//use App\Services\Mq\ConsumerMqService;
//use App\Services\Mq\ProductMqService;
use App\Jobs\Withdrawal;
use App\Services\RmqClientService;
use Illuminate\Http\Request;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class QueueController extends Controller
{
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }


    /**
     * FunctionName：adopt
     * Description：审核通过
     * Author：lwl
     */
    public function adopt()
    {
        //我将用户提现申请，审核通过 我生产一条消息 等待资金服务消费去做资金改动
        $withdrawalId = 101;//提现id
        event(new WithdrawalEvent(['withdrawal_id' => $withdrawalId]));
    }

    /**
     * FunctionName：product
     * Description：生产
     * Author：lwl
     * @return string
     */
    public function product()
    {
        $exchange = 'message';
        $queue = 'lwl';
        $conn = new AMQPStreamConnection( //建立生产者与mq之间的连接
            'xb_rabbitmq', '5672', 'guest', 'guest', '/'
        );
        $channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道
        $channel->exchange_declare($exchange, 'direct', false, true, false); //声明初始化交换机
        $channel->queue_declare($queue, false, true, false, false); //声明初始化一条队列
        $channel->queue_bind($queue, $exchange); //将队列与某个交换机进行绑定，并使用路由关键字
        $msgBody = json_encode(['name' => 'lwl', 'age' => 27]);
        $msg = new AMQPMessage($msgBody, ['content_type' => 'text/plain', 'delivery_mode' => 2]); //生成消息
        $result = $channel->basic_publish($msg, $exchange); //推送消息到某个交换机
        $channel->close();
        $conn->close();
    }

    /**
     * FunctionName：consumer
     * Description：消费
     * Author：lwl
     */
    public function consumer()
    {
        try {
            (new ConsumerMqService())->run();
        } catch (\Exception $exception) {
            dd($exception->getMessage());
        }
    }

    public function mq()
    {
        Queue::dispatch();
    }
}
